import superagent from 'superagent';
import config from 'config';

const methods = ['get', 'post', 'put', 'patch', 'del'];

function formatUrl(path) {
  const adjustedPath = path[0] !== '/' ? '/' + path : path;
  return config.api.host + adjustedPath;
}

class Request {
  constructor() {
    methods.forEach((method) =>
      this[method] = (path, { params, data, sessionToken, masterKey } = {}) => new Promise((resolve, reject) => {
        const request = superagent[method](formatUrl(path));
        request.set('X-Parse-Application-Id', config.api.appId);
        if (sessionToken) {
          request.set('X-Parse-Session-Token', sessionToken);
        }

        if (masterKey) {
          request.set('X-Parse-Master-Key', masterKey);
        }

        if (params) {
          request.query(params);
        }

        if (data) {
          request.send(data);
        }

        request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
      }));
  }
  empty() {}
}

const request = new Request();
export default request;
